﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using Scrabble.Tasks;
using Scrabble.ViewModels;

namespace Scrabble.Views
{
    public partial class BoardView
    {
        private readonly KeyConverter _keyConverter = new KeyConverter();

        public BoardView()
        {
            InitializeComponent();

            Focusable = true;
            KeyDown += OnInPlaceEditorKeyDown;
        }

        private void OnPreviewMouseLeftButtonDownInSquare(object sender, MouseButtonEventArgs args)
        {
            var element = sender as FrameworkElement;
            if (element == null) return;

            var square = element.DataContext as Square;
            if (square == null) return;
                
            square.Select();
            Focus();
        }

        private IPlayingContext PlayingContext
        {
            get { return ((FrameworkElement) InputBox.Content).DataContext as IPlayingContext; }
        }

        private void OnInPlaceEditorKeyDown(object sender, KeyEventArgs e)
        {
            if (sender != this || PlayingContext == null) return;

            e.Handled = true;

            try
            {
                switch (e.Key)
                {
                    case Key.Return:
                        PlayingContext.PlayProposedWord();
                        break;
                    case Key.Escape:
                        PlayingContext.CancelPlay();
                        break;
                    case Key.Back:
                        PlayingContext.ReturnLastTileToRack();
                        break;
                    default:
                        if (e.Key >= Key.A && e.Key <= Key.Z)
                            // ReSharper disable AssignNullToNotNullAttribute
                            PlayingContext.PlayTileFromRack(_keyConverter.ConvertToString(e.Key).First());
                            // ReSharper restore AssignNullToNotNullAttribute
                        else
                            e.Handled = false;
                        break;
                }
            }
            catch (Exception exception)
            {
                Show.Notification(exception.Message).Execute();
            }
        }
    }
}
